package cn.infinite.security.handler;

import cn.easier.club.base.dto.ResultInfo;
import cn.infinite.security.configuration.SmsConfigurerProperties;
import cn.infinite.security.util.HttpProtocolUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhangqi
 */
@Slf4j
public class DefaultSmsAuthenticationSuccessHandlerImpl implements SmsAuthenticationSuccessHandler {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    private RequestCache requestCache = new HttpSessionRequestCache();

    private SmsConfigurerProperties smsConfigurerProperties;

    public DefaultSmsAuthenticationSuccessHandlerImpl(SmsConfigurerProperties securityBasicProperties) {
        this.smsConfigurerProperties = securityBasicProperties;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication
            authentication) throws IOException, ServletException {
        String accept = request.getHeader(HttpHeaders.ACCEPT);
        log.info("authenticate success, accept response content-type is =>{}", accept);
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        String redirectUrl = savedRequest != null ? HttpProtocolUtil.parseToHttps(savedRequest.getRedirectUrl())
                : this.smsConfigurerProperties.getAuthenticateSuccessUrl();
        if (savedRequest != null) {
            log.info("last saved request url =>{}", savedRequest.getRedirectUrl());
        }

        if (StringUtils.equalsIgnoreCase(MediaType.TEXT_HTML_VALUE, accept) || StringUtils.containsIgnoreCase
                (accept, MediaType.TEXT_HTML_VALUE)) {

            log.info("redirect to saved request url =>{}", authentication.getPrincipal());
            this.redirectStrategy.sendRedirect(request, response, redirectUrl);
        } else {
            ResultInfo<String> resultInfo = new ResultInfo("ok", HttpStatus.OK.getReasonPhrase(), redirectUrl);
            response.getWriter().write(JSON.toJSONString(resultInfo));
            response.getWriter().close();
        }
    }
}
